console.log('生命周期', this);
const requestGet = (url) => {
  const headers = { "Content-Type": "application/json" };
  return fetch(url, { headers }).then(res => res.json())
};
// 路由参数
let params      = this.getVariables().find(v => v.name === "screen_params")?.value;
// 请求前缀
const prefix    = this.getVariables().find(v => v.name === "environmentType")?.value;
// 获取页面组件
const disposition   = this.getApiWidgetByAliasName('list')?.widgetObj;
const tabList       = this.getApiWidgetByAliasName('演练标签页');
const widgetsGis    = this.getApiWidgetByAliasName('三维组件')?.widgetObj;
const $playback     = this.getApiWidgetByAliasName('playback');
const $form         = this.getApiWidgetByAliasName('judge-content');
const $formEdit     = this.getApiWidgetByAliasName('change-form');
const $img          = this.getApiWidgetByAliasName('detail-img');
const Modal = tabList.widgetObj.getModal();
const whetherProcess = [
  { name: '未处理', value: 0 },
  { name: '已处理', value: 1 },
  { name: '处理中', value: 2 },
  { name: '已解除', value: 3 },
  { name: '误警', value: 4 },
]

if (params) {
  try {
    params = JSON.parse(params)
    this.setVariables([{ name: 'eventId', value: params.id }])
  } catch (e) {
    console.error(e)
  }
}
// 演练中
this.getApiWidgetByAliasName('modal-btns')?.widgetObj.renderDrilling();

if(params) {
  this.setVariables([{ name: 'update', value: params.id }]);
  params.eventId = params.id
  disposition.setEvent(params);
  disposition.setParams(params.id);
  disposition.initQuery()
}
console.log('生命周期', params);
const getEnums = () => {
  const levels = this.getDataById('744574925553008640');
  const types = this.getDataById('744575296061046784');
  const qualitys = this.getDataById('756194853578080256');
  return {
    eventTypeCode: types?.data,
    eventGradeCode: levels?.data,
    eventQualityCode: qualitys?.data,
    disableFlag: [
      { name: '未演练', value: 0 },
      { name: '已编制', value: 1 },
      { name: '处理中', value: 2 },
      { name: '已解除', value: 3 },
      { name: '误警', value: 4 },
    ],
  }
}
/**
 * 打开实时视频
 */
function playingCamera() {
  if (params.sourceDeviceId) {
    requestGet(`/${prefix}Basics/basics-main/system/equipmentObject/listDetailByEquipmentCode?equipmentCode=${params.sourceDeviceId}`)
        .then(({ success, result } = {}) => {
          if (success && result && result.rows && result.rows[0]) {
            const { equipmentConfig } = result.rows[0];
            const config = equipmentConfig?.gbVideoConfig;
            if (config) {
              const { sipUser, videoChannelId } = config;
              var host = this.getVariables().find(x => x.name == "stream_url").value;
              if (sipUser && videoChannelId) {
                widgetsGis.sullivan.close();
                widgetsGis.sullivan.addPlayer(`${host}/api/v1/stream/rtc/play`, `${sipUser}/${videoChannelId}`);
                widgetsGis.sullivan.initial()
              } else {
                window.layer.msg('暂无设备号/通道号')
              }
            } else {
              window.layer.msg('暂无设备号/通道号')
            }
          }
        })
  } else {
    window.layer.msg('未关联摄像头')
  }
}

/**
 * 处理回放
 */
function playBackHistory(detail) {
  let data = getDetail(detail);
  console.log('playBackHistory:detail: => ', data);
  if (data && Object.keys(data).length > 0) {
    // 关闭三维弹窗
    widgetsGis.gisMap.setModalType('NONE');
    // 回放
    if (data.jpbPath) {
      $playback.widgetObj.setData([{ data: data?.jpbPath }]);
      $playback.showWidget();
      $playback.widgetObj.render();
    } else {
      $playback.hideWidget();
      window.layer.msg('暂无录像回放')
    }

  } else {
    $playback.hideWidget();
    window.layer.msg('暂无录像回放')
  }
}

// 处理表单 - 详情
const executeForm = (detail) => {
  detail = getDetail(detail);
  const formData = { ...params, eventPoint: params.pointId };

  // 详情时隐藏上传功能
  $form.widgetObj._option.config.forEach(v => {
    if (v.type === 'upload' || v.dataIndex === 'sourceDeviceId') {
      v.visible = true
    }
  });

  // 添加枚举列表
  $form.widgetObj._option.options = getEnums();

  // 渲染详情
  // $form.widgetObj._option.dataSource = formData;
  $form.widgetObj._option.isDetail = true;
  $form.widgetObj.setFormData('form_20', formData);

  console.log('变更演练', $formEdit.widgetObj._option)
  // $formEdit.widgetObj._option.dataSource = formData;
  $formEdit.widgetObj.setFormData('form_19', formData);

  // 显示详情图片
  if (detail?.thumbnailPath) {
    const srcArr = detail.thumbnailPath.split(',').map(v => ({ src: v }));
    $img.widgetObj.setData([{ data: srcArr }]);
    $img.widgetObj.render()
  } else {
    $img.widgetObj.setData([{ data: [] }]);
    $img.widgetObj.render()
  }
};

const executeSummary = () => {
  const summary = this.getApiWidgetByAliasName('演练概述')?.widgetObj;
  if (summary) {
    // 添加枚举列表
    summary._option.options = getEnums();

    console.log('executeSummary: => ', summary._option, params);
    // 渲染详情
    summary._option.dataSource = params;
    summary._option.isDetail = true;
    summary.render();
  }
};
function getDetail (detail) {
  try {
    if (typeof data === 'string') detail = JSON.parse(eventDetails)
  } catch (err) {
    detail = eventDetails;
    console.error(err)
  }

  return detail
}
if (params) {
  let { eventDetails } = params;
  Modal.defaultData = params;

  // 设置三维组件定位
  if (widgetsGis) {
    widgetsGis.artemis.setEmergencyId(params.id);
    widgetsGis.setIconPosition({ right: 570, top: 100 });
    widgetsGis.setModalPosition({ right: 965, bottom: 24 });
  }

  // 处理回放
  playBackHistory(eventDetails);
  // 打开实时视频
  playingCamera();
  // 处理表单
  executeForm (eventDetails);
  // 事件概览
  executeSummary();
} else {
  // 隐藏右边所有的方案
  const collaspe_list = this.getApiWidgetsByClassName('disposition');
  collaspe_list?.forEach(v => v.hideWidget());
  // 重置 ICON 位置
  widgetsGis.setIconPosition({ right: 20, top: 100 });
  widgetsGis.setModalPosition({ right: 5, bottom: 20 })
}
